<?php

namespace Common\Service;

use Common\Service\SignatureHelper;
use Think\Exception;
use Think\Log;

/**
 * 发送短信
 */
class Sms
{
    /**
     * @param $mobile
     * @param string $type 目前有验证码，通知类型
     * @return string
     */
    public static function sendCode($mobile, $type = 'yzm')
    {
        try {
            $conf = C('sms_config');
            //获取指定长度的验证码
            $code = SELF::getCode(6);
            $apikey = $conf['apikey'];
            if ($type == 'yzm') {//模板,url
                $content = sprintf($conf['yzm']['content'], $code);
                $url = $conf['yzm']['url'];
            }
            $headers = [
                'Accept:text/plain;charset=utf-8',
                'Content-Type:application/x-www-form-urlencoded',
                'charset=utf-8'
            ];
            $params = [
                'apikey' => $apikey,
                'mobile' => $mobile,
                'content' => urlencode($content)
            ];

            $ret = json_decode(Curl::request('post', $url, $params, $headers), true);
            if ($ret['code'] == 1) {
                S($mobile, $code, 600);
                return true;
            } else {
                Log::write('验证码发送失败：' . $ret['msg']);
                return false;
            }

        } catch (\Exception $e) {
            Log::write('验证码发送失败：' . $e->getMessage() . '---' . $e->getCode());
            return false;
        }
    }

    /**
     * 指定长度的数字字符串
     * @param $len
     * @return string
     */
    private static function getCode($len)
    {
        $code = '';
        for ($i = 0; $i < $len; $i++) {
            $randcode = mt_rand(0, 9);
            $code .= $randcode;
        }
        return $code;
    }
}